import React, { useRef } from 'react';
import { useModel } from 'umi';
import { Card, Empty, Popconfirm } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import * as utils from '@/utils/utils';

import * as api from '@/services/user';

const getLoginInfo = (user: API.Device) => {
  let info = '';
  info += `${user.loginCountry} ${user.loginProvince} ${user.loginCity}`;
  if (user.loginNet && user.loginNet.indexOf('内网') == -1) {
    info += ` [${user.loginNet}]`;
  }

  return info;
};

export type UserDeviceTableProps = {
  userId?: string;
};

const UserDeviceTable: React.FC<UserDeviceTableProps> = (props) => {
  const { userId } = props;

  if (!userId) {
    return (
      <Card style={{ marginTop: 20, minHeight: 200 }}>
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={<span>暂无数据</span>}
        ></Empty>
      </Card>
    );
  }

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const { getProduct } = useModel('useGlobalModel', (model) => ({
    getProduct: model.getProduct,
  }));

  const handleRemove = async (id: string) => {
    const result = await api.removeDevice({ key: id });

    console.log('result: ', result);
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.UserDeviceModel>[] = [
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productId',
      sorter: true,
      renderText: (_, record) => {
        if (record.productId) {
          const product = getProduct(record.productId);
          if (product) {
            return product.name;
          }
        }
        return '';
      },
    },
    {
      title: '平台',
      // align: 'center',
      width: 140,
      dataIndex: 'platform',
      sorter: true,
    },
    {
      title: '版本',
      align: 'center',
      width: 60,
      dataIndex: 'ver',
      sorter: true,
    },
    {
      title: '时区',
      align: 'center',
      width: 80,
      dataIndex: 'timezone',
      sorter: true,
    },
    {
      title: '语言',
      align: 'center',
      width: 80,
      dataIndex: 'lang',
      sorter: true,
    },
    {
      title: '渠道',
      // align: 'center',
      width: 100,
      dataIndex: 'channel',
      sorter: true,
    },
    {
      title: '设备ID',
      dataIndex: 'deviceid',
      sorter: true,
    },
    {
      title: '设备型号',
      dataIndex: 'deviceModel',
      sorter: true,
    },
    {
      title: '设备系统',
      dataIndex: 'deviceOs',
      sorter: true,
    },
    {
      title: '注册时间',
      align: 'center',
      dataIndex: 'loginTime',
      sorter: true,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.loginTime);
      },
    },
    {
      title: '注册IP',
      align: 'center',
      width: 120,
      dataIndex: 'loginIp',
      sorter: true,
    },
    {
      title: '注册地址',
      render: (_, record) => {
        return (
          <>
            <span>{getLoginInfo(record)}</span>
          </>
        );
      },
    },
    {
      title: '绑定时间',
      align: 'center',
      dataIndex: 'bindTime',
      sorter: true,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.bindTime);
      },
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('user_deletedevice')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.userDeviceId);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <Card style={{ marginTop: 20, minHeight: 200 }} title="用户设备">
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        headerTitle="用户设备"
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        columnEmptyText={''}
        columns={columns}
        search={false}
        toolBarRender={false}
        pagination={{
          defaultPageSize: 15,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
          // current: pageCurrent,
          // total: totalCount,
        }}
        params={{ userId }}
        request={api.getDevices}
      />
    </Card>
  );
};

export default UserDeviceTable;
